package cloudspace.ui.impl;

import org.zkoss.zk.ui.Component;
import org.zkoss.zk.ui.event.Event;
import org.zkoss.zk.ui.event.EventListener;
import org.zkoss.zk.ui.util.GenericComposer;
import org.zkoss.zul.Bandbox;
import org.zkoss.zul.Textbox;
import org.zkoss.zul.Tree;
import org.zkoss.zul.Window;

import cloudspace.controlpanel.filemanager.CSPathDirectoryTreeModel;
import cloudspace.controlpanel.filemanager.CSPathTreeitemRenderer;
import cloudspace.controlpanel.filemanager.FileManagerModel;
import cloudspace.vm.filesystem.CSPath;


public class NewUserDialog extends GenericComposer
{
    // ~ Static/instance variables .............................................

    private static final long serialVersionUID = 6081953395500563691L;

    private Tree directoryTree;

    private Bandbox userDirectoryLocation;

    private Textbox usernameBox;

    private CSPath path;

    private Window window;


    // ~ Constructors ..........................................................

    // ----------------------------------------------------------
    public NewUserDialog()
    {
        path = null;
    }


    @Override
    @SuppressWarnings("unchecked")
    public void doAfterCompose( Component component ) throws Exception
    {
        window = (Window)component;
        window.setAttribute( "composer", this );
        usernameBox = (Textbox)component.getFellow( "userNameBox" );
        directoryTree = (Tree)component.getFellow( "directoryTree" );
        userDirectoryLocation = (Bandbox)component.getFellow( "userDirectoryLocation" );
        directoryTree.setModel( new CSPathDirectoryTreeModel( new FileManagerModel() ) );
        directoryTree.setTreeitemRenderer( new CSPathTreeitemRenderer() );
        directoryTree.addEventListener( "onSelect", new EventListener()
        {

            public void onEvent( Event event ) throws Exception
            {
                onDirectoryTreeSelect( event );

            }

        } );
        userDirectoryLocation = (Bandbox)component.getFellow( "userDirectoryLocation" );
    }


    // ~ Methods ...............................................................

    // ----------------------------------------------------------
    // ----------------------------------------------------------
    public void onDirectoryTreeSelect( Event event )
    {
        path = (CSPath)directoryTree.getSelectedItem().getValue();
        userDirectoryLocation.setValue( path.getQualifiedPath() );
        userDirectoryLocation.close();
    }

    public void cancel(Event event)
    {
        cancel();
    }

    public void cancel()
    {
        path = null;
        window.detach();
    }


    // ----------------------------------------------------------
    public CSPath getResult()
    {
        return path;
    }


    public String getUserName()
    {
        return usernameBox.getValue();
    }

}
